<?php

namespace App\Api\Service;

use App\Api\Repositories\User\UsersRepositories;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Http;
use Laravel\Socialite\Facades\Socialite;

class UserService
{
    protected $repositories;

    public function __construct()
    {
        $this->repositories = new UsersRepositories();
    }

    /**
     * 修改会员数据
     *
     * @param int $uid 会员id
     * @param array $field_values 字段和值组成键值对的数组
     * @return void
     */
    public function update_data($uid, $field_values)
    {
        $data = [];
        foreach ($field_values as $field => $value) {
            $data[$field] = $value;
        }
        return $this->repositories->update_data($uid, $data);
    }

    /**
     * 更新个人信息
     * 如果不是第一次修改，则需要扣款
     *
     * @param [type] $uid
     * @param [type] $field_values
     * @return void
     */
    public function update_detail($uid, $field_values)
    {
        DB::beginTransaction();
        try {
            if ($this->repositories->judge_update_need_pay($uid)) {
                $this->deduct($uid, '编辑信息', '编辑相亲信息');
            }
            $this->update_data($uid, $field_values['user']);
            $user_detail_repositories = new \App\Api\Repositories\User\UserDetailRepositories();
            $res = $user_detail_repositories->update_data($uid, $field_values['user_detail']);
            if (!$res) {
                throwBusinessException('更新失败');
            }
            DB::commit();
            return true;
        } catch (\Exception $e) {
            DB::rollBack();
            throwBusinessException($e->getMessage());
        }
    }

    /**
     * 获取相亲名片所需数据
     *
     * @param int $uid
     * @return void
     */
    public function get_user_detail($uid, $pay_uid = 0)
    {
        if ($pay_uid != 0) {
            $user_funds_r = new \App\Api\Repositories\User\UserFundsRepositories();
            $sys_setting_r = new \App\Api\Repositories\Sys\SysSettingRepositories();
            $res = $user_funds_r->update_data($pay_uid, 'money', -1 * $sys_setting_r->get(28), '会员id搜索', '搜索会员id为' . $uid . '的相亲信息');
            if (!$res) {
                throwBusinessException('积分扣除失败');
            }
            $log_user_browse = new \App\Api\Repositories\Log\LogUserBrowseRepositories();
            $log_user_browse->set_is_read('i' . $uid, $pay_uid);
        }
        $user_select = ['id', 'nickname', 'avatar'];
        $user_data = $this->repositories->get_data('id', $uid, $user_select);
        $user_detail_repositories = new \App\Api\Repositories\User\UserDetailRepositories();
        $user_detail_data = $user_detail_repositories->use_id_get_data($uid)->toArray();
        $user_data->photo_number = 0;
        $array = ['general_photo', 'life_photo', 'work_photo', 'study_photo', 'travel_photo', 'other_photo'];
        foreach ($user_detail_data as $key => $value) {
            if (in_array($key, $array)) {
                $value != '' ? $user_data->photo_number++ : '';
            }
            $user_data->$key = $value;
        }
        $user_data->is_fill_out = $this->repositories->judge_update_need_pay($uid);  # 为了判断是否填写信息
        // 获取是否已收藏
        $log_user_collect = new \App\Api\Repositories\Log\LogUserCollectRepositories();
        $user_data->is_collect = $log_user_collect->get_is_collect('i' . $uid, $pay_uid);
        $user_data->search_id = 'i' . $uid;
        if ($pay_uid != 0) {
            // 联系方式付费
            $log_user_fund = new \App\Api\Repositories\Log\LogUserFundRepositories();
            foreach (['email', 'qq', 'weixin'] as $field) {
                $key = "is_show_" . $field;
                $user_data->$key = false;
                if ($user_data->$field != '') {
                    $user_data->$field = '******';
//                    $user_data->$key = boolval($log_user_fund->get_show_content_log($pay_uid, 'i' . $uid . $field));
//                    if ($user_data->$key == false) {
//                        $user_data->$field = '******';
//                    }
                }
            }
        }
        return $user_data;
    }

    /**
     * 登录操作，获取会员信息并设置token
     *
     * @param string $field 会员标识
     * @param string $value 值
     * @param string $type 登录类型，其中密码登录，第三方登录不能在登录时注册
     * @return void
     */
    public function login($field, $value, $type = 'password', $create_data = [])
    {
        $user = $this->repositories->get_data($field, $value);
        if ($user->is_login == 0) {
            throwBusinessException('账号已被禁止登录');
        }
        $data = [
            'uid' => $user->id,
            'avatar' => $user->avatar,
            'phone' => $user->phone,
        ];
        if (!in_array($type, ['password', 'third_party'])) {
            $data['is_register'] = 0;
            if (!$user) {  // 注册
                $user = $this->repositories->create_data($value, '', 0, $create_data);
                $data['is_register'] = 1;
            }
        }

        $data['token'] = $this->repositories->set_token($user->id);
        $this->repositories->update_data($user->id, ['login_ip' => request()->ip(), 'login_time' => date('Y-m-d H:i:s', time())], $data['token']);
        return $data;
    }

    /**
     * 微信小程序登录
     *
     * @param string $code
     * @return void
     */
    public function wxmini_login($code, $iv, $encryptedData, $parent_id)
    {
        $sys_setting_repositories = new \App\Api\Repositories\Sys\SysSettingRepositories();
        $appid = $sys_setting_repositories->get(16);
        $secret = $sys_setting_repositories->get(17);
        $api = "https://api.weixin.qq.com/sns/jscode2session?appid={$appid}&secret={$secret}&js_code={$code}&grant_type=authorization_code";
        $res = json_decode(Http::get($api), true);
        if (!empty($res['errcode'])) {
            throwBusinessException($res['errcode']);
        }
        $sessionKey = $res['session_key'];
        $openid = $res['openid'];
        if ($iv != '' && $encryptedData != '') {
            $res = $this->decryptData($appid, $sessionKey, $encryptedData, $iv);
            $nickname = $res['nickName'];
            $avatar = $res['avatarUrl'];
        } else {
            $nickname = '游客';
            $avatar = '';
        }
        $user = $this->repositories->get_data('openid', $openid);
        if (!$user) {
            $user = $this->repositories->create_data('', '', 0, [
                'login_type' => 'wxmini',
                'nickname' => $nickname,
                'avatar' => $avatar,
                'openid' => $openid,
                'parent_id' => $parent_id
            ]);
            if ($parent_id != 0) {
                $user_funds_r = new \App\Api\Repositories\User\UserFundsRepositories();
                $sys_setting_r = new \App\Api\Repositories\Sys\SysSettingRepositories();
                $user_funds_r->update_data($parent_id, 'money', $sys_setting_r->get(24), '分享', '会员id-' . $user->id . '通过分享注册');
            }
        }
        return $user;
    }

    /**
     * 通过token获取到会员id
     *
     * @param string $token token
     * @return void
     */
    public function use_token_get_uid($token)
    {
        return $this->repositories->use_token_get_uid($token);
    }

    /**
     * 通过会员id获取到会员对象
     * 添加了三个红点属性
     * 添加会员积分信息
     * 添加被浏览收藏量
     *
     * @param int $uid 会员id
     * @return void
     */
    public function use_id_get_data($uid, $number)
    {
        $data = $this->repositories->get_data('id', $uid);
        $red_dots = $this->repositories->get_red_dots($uid);
        foreach ($red_dots as $key => $value) {
            $data->$key = $value;
        }
        $data->update_need_pay = $this->repositories->judge_update_need_pay($uid);
        $log_user_browse_r = new \App\Api\Repositories\Log\LogUserBrowseRepositories();
        $data->be_browse_number = $log_user_browse_r->get_user_be_browse_count($uid);
        $log_user_collect_r = new \App\Api\Repositories\Log\LogUserCollectRepositories();
        $data->be_collect_number = $log_user_collect_r->get_user_be_collect_count($uid);
        if ($data->qrcode == '') {
            $wxmini_qrcode_service = new \App\Api\Service\Trigonal\WxminiQrcodeService();
            $wxmini_qrcode_service->get_qrcode($uid, 1);
            $wxmini_qrcode_service->get_qrcode($uid, 2);
            $data->qrcode = "https://www.chixin.vip/uploads/qrcode/" . $uid . '.png';
            $this->repositories->update_data($uid, ['qrcode' => $data->qrcode]);
        }
        $data->qrcode_index = "https://www.chixin.vip/uploads/qrcode/" . $uid . '_index.png';
        // $data->qrcode = "http://image.chixin.club/images/gh_cb8b3711b8f6_258.jpg";
        return $data;
    }

    /**
     * 将会员红点数据更新为当天
     *
     * @param int $uid
     * @param string $type
     * @return bool
     */
    public function set_red_dot($uid, $type)
    {
        return $this->repositories->set_red_dot($uid, $type);
    }

    /**
     * 获取积分与分享奖励统计信息
     *
     * @param int $uid
     * @return void
     */
    public function get_integrate_data($uid)
    {
        $user_funds_r = new \App\Api\Repositories\User\UserFundsRepositories();
        $integrate = $user_funds_r->get_money($uid);
        $log_user_funds_r = new \App\Api\Repositories\Log\LogUserFundRepositories();
        $invite_awary_sum = $log_user_funds_r->get_type_sum($uid, '分享');
        return ['integrate' => $integrate, 'invite_awary_sum' => $invite_awary_sum];
    }

    public function deduct($uid, $type, $content, $remark = '')
    {
        $user_funds_r = new \App\Api\Repositories\User\UserFundsRepositories();
        $sys_setting_r = new \App\Api\Repositories\Sys\SysSettingRepositories();
        $res = $user_funds_r->update_data($uid, 'money', -1 * $sys_setting_r->get(26), '编辑信息', '编辑相亲信息');
        if (!$res) {
            throwBusinessException('扣款失败');
        }
    }


    /**
     * 检验数据的真实性，并且获取解密后的明文.
     * @param $encryptedData string 加密的用户数据
     * @param $iv string 与用户数据一同返回的初始向量
     * @param $data string 解密后的原文
     *
     * @return array 返回数据
     */
    private function decryptData($appid, $sessionKey, $encryptedData, $iv)
    {
        if (strlen($sessionKey) != 24) {
            throwBusinessException('encodingAesKey 非法');
        }
        $aesKey = base64_decode($sessionKey);
        if (strlen($iv) != 24) {
            throwBusinessException('aes 解密失败');
        }
        $aesIV = base64_decode($iv);
        $aesCipher = base64_decode($encryptedData);
        $result = openssl_decrypt($aesCipher, "aes-128-cbc", $aesKey, OPENSSL_RAW_DATA, $aesIV);
        $dataObj = json_decode($result);
        if ($dataObj == NULL) {
            throwBusinessException('解密后得到的buffer非法');
        }
        if ($dataObj->watermark->appid != $appid) {
            throwBusinessException('base64解密失败');
        }
        $data = json_decode($result, true);
        return $data;
    }

    function decode($text)
    {
        $pad = ord(substr($text, -1));
        if ($pad < 1 || $pad > 32) {
            $pad = 0;
        }
        return substr($text, 0, (strlen($text) - $pad));
    }
}
